import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { NzNotificationService } from 'ng-zorro-antd';

import { UsermanegeService, Role } from '../../../DM/usermanege.service';
@Component({
  selector: 'app-user-registe',
  templateUrl: './user-registe.component.html',
  styleUrls: ['./user-registe.component.css'],
})
export class UserRegisteComponent implements OnInit {

  _roleLs: Role[] = [];
  _currentStep: number = 0;
  _registeUserForm: FormGroup;
  constructor(
    private usermanageService: UsermanegeService,
    private fb: FormBuilder,
    private router: Router,
    private msgService: NzMessageService,
    private noticeService: NzNotificationService,
  ) {
    this.usermanageService.stepsEmit.emit(0);
    this._registeUserForm = this.fb.group({
      'username': ['', [Validators.required]],
      'password': ['', [Validators.required]],
      'repeatPassword': ['', [Validators.required, this._repeatPwdValidtor()]],
      'role': ['', [Validators.required]],
    });
  }

  async ngOnInit() {
    this._roleLs = await this.usermanageService.getRoleLs();
  }

  getFormControl(controlname: string) {
    return this._registeUserForm.controls[controlname];
  }

  async _submitForm() {
    for (const i in this._registeUserForm.controls) {
      this._registeUserForm.controls[i].markAsDirty();
    }
    if (this._registeUserForm.valid) {
      try {
        let id = await this.usermanageService.createUser(this._registeUserForm.value.username, this._registeUserForm.value.password, this._registeUserForm.value.role);
        this.msgService.success('注册成功');
        this.noticeService.blank('注册用户', '您刚刚注册了一个用户。');
        this.router.navigate(['/back/user/authorization', id, true]);
      } catch (err) {
        this.msgService.success('注册失败');
        this.noticeService.blank('注册用户', `由于${err}，您注册用户失败。`);
      }
    }
  }

  // repeatpwdvalidtor
  _repeatPwdValidtor(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      if (!this._registeUserForm) return { 'repeat': true };
      return control.value == this._registeUserForm.get('password').value ? null : { 'repeat': true };
    }
  }

}